package com.lsx143.wordcount.day8;

import com.lsx143.wordcount.bean.AdsClickLog;
import com.lsx143.wordcount.bean.GoodState;
import com.lsx143.wordcount.bean.UserBehavior;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.state.ReducingState;
import org.apache.flink.api.common.state.ReducingStateDescriptor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.TypeHint;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.SlidingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.TreeSet;

public class Flink_Black {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        OutputTag<String> blackListTag = new OutputTag<String>("blackListStream") {
        };
        env
                .setParallelism(1);
        SingleOutputStreamOperator<String> process = env
                .readTextFile("input/AdClickLog.csv")
                .map(line -> {
                    String[] datas = line.split(",");
                    return new AdsClickLog(Long.valueOf(datas[0]),
                            Long.valueOf(datas[1]),
                            datas[2],
                            datas[3],
                            Long.parseLong(datas[4]) * 1000L);
                })
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<AdsClickLog>forBoundedOutOfOrderness(Duration.ofSeconds(20))
                                .withTimestampAssigner(new SerializableTimestampAssigner<AdsClickLog>() {
                                    @Override
                                    public long extractTimestamp(AdsClickLog element, long recordTimestamp) {
                                        return element.getTimestamp() * 1000L;
                                    }
                                }))
                .keyBy(log -> log.getUserId() + "_" + log.getAdId())
                .process(new KeyedProcessFunction<String, AdsClickLog, String>() {

                    private ValueState<String> dayState;
                    private ValueState<Boolean> warnState;
                    private ReducingState<Long> reducingState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        reducingState = getRuntimeContext().getReducingState(new ReducingStateDescriptor<>("reducingState", Long::sum, Long.class));
                        warnState = getRuntimeContext().getState(new ValueStateDescriptor<>("warnState", Boolean.class));
                        dayState = getRuntimeContext().getState(new ValueStateDescriptor<>("dayState", String.class));
                    }

                    @Override
                    public void processElement(AdsClickLog log,
                                               Context ctx,
                                               Collector<String> out) throws Exception {
                        String today = new SimpleDateFormat("yyyy-MM-dd").format(log.getTimestamp());
                        String date = dayState.value();
                        if (!today.equals(date)) {
                            dayState.update(today);
                            warnState.clear();
                            reducingState.clear();
                        }
                        if (warnState.value() == null) {
                            reducingState.add(1L);
                        }
                        long clickCount = reducingState.get();
                        String msg = log.getUserId() + " 对 " + log.getAdId() + "的点击量是：" + clickCount;
                        if (clickCount > 99) {
                            if (warnState.value() == null) {
                                warnState.update(true);
                                ctx.output(blackListTag, msg);
                            }
                        } else {
                            out.collect(msg);
                        }
                    }
                });
        process.print("正常用户");
        process.getSideOutput(blackListTag).print("黑名单：");
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}